package com.wzt.lianfirecontrol.fragment.xuncha;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.adapter.xuncha.XunChaSelectBuildAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaBuildingModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaFloorModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.XunChaPlanModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class StartXunChaFragment extends BaseFragment{

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private RecyclerView rlv_info_list;
    private XunChaSelectBuildAdapter baseRecyclerAdapter;
    private LinearLayoutManager llm_info_list;

    /**
     * 底部
     */
    private LinearLayout ll_all_choose;
    private ImageView iv_all_choose;
    private boolean isAllChoose = false;

    private Button bt_start_check;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private XunChaPlanModel xunChaPlanModel;

    private static final int CHECK_PLAN_STATUS_WHAT = 0;
    private static final int START_XUNCHA_WHAT = 1;

    private ArrayList<XunChaBuildingModel> xunChaBuildingModels = new ArrayList<>();
    private List<String> floorIdList = new ArrayList<>();
    private List<String> quesFloorIds = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            activity = getMyActivity();
            bundle = getArguments();
            if (bundle != null){
                xunChaPlanModel = (XunChaPlanModel) bundle.getSerializable("data");
            }
            if (null == xunChaPlanModel){
                activity.finish();
            }
            itemContentView = inflater.inflate(R.layout.f_start_xuncha, container, false);
            initView();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        initListView();

        initBottomView();

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initListView() {
        rlv_info_list = itemContentView.findViewById(R.id.rlv_info_list);
        llm_info_list = new LinearLayoutManager(activity);
        llm_info_list.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_info_list.setLayoutManager(llm_info_list);

        baseRecyclerAdapter = new XunChaSelectBuildAdapter(activity);
        baseRecyclerAdapter.setXunChaPlanModel(xunChaPlanModel);
        rlv_info_list.setAdapter(baseRecyclerAdapter);
    }

    private void initBottomView() {
        ll_all_choose = itemContentView.findViewById(R.id.ll_all_choose);
        iv_all_choose = itemContentView.findViewById(R.id.iv_all_choose);
        ll_all_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAllChoose = !isAllChoose;
                if (isAllChoose){
                    iv_all_choose.setImageResource(R.mipmap.icon_single_select);
                }else {
                    iv_all_choose.setImageResource(R.mipmap.icon_all_choose);
                }
                if (null != baseRecyclerAdapter && baseRecyclerAdapter.getmDatas().size() > 0){
                    for (XunChaBuildingModel buildModel:baseRecyclerAdapter.getmDatas()){
                        if (null != buildModel.getChildren() && buildModel.getChildren().size() > 0) {
                            for (XunChaFloorModel xunChaFloorModel : buildModel.getChildren()) {
                                xunChaFloorModel.setCurrentSelectStatus(isAllChoose ? "1" : "0");
                            }
                        }
                    }
                    baseRecyclerAdapter.notifyDataSetChanged();
                }
            }
        });

        bt_start_check = itemContentView.findViewById(R.id.bt_start_check);
        List<String> alias = UserInfoModel.getUserInfo(getActivity()).getRoleAlias();
        // 维保人员和维保管理人员只显示预约维保单
        // 组织管理员 ROLE_ORG_MANAGER  先判断是否是组织管理员，是，就只能看，不能操作。不是的话，判断是否是维保人员

        if (alias.contains(RoleConstant.ROLE_ORG_MANAGER)) {

            bt_start_check.setVisibility(View.GONE);

        }else {

            bt_start_check.setVisibility(View.VISIBLE);

        }




        bt_start_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserInfoModel.isSelfCompany(activity)){
            //        ToastUtils.showToast(activity, ConstData.ERROR_COMPANY_MSG);
                    return;
                }
                UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
                if (!userInfoModel.getRoleAlias().contains(RoleConstant.ROLE_INSPECTION)){
                    ToastUtils.showToast(activity, "无权限");
                    return;
                }

                xunChaBuildingModels.clear();
                floorIdList.clear();
                quesFloorIds.clear();
                if (null != baseRecyclerAdapter && baseRecyclerAdapter.getmDatas().size() > 0){
                    for (XunChaBuildingModel buildModel:baseRecyclerAdapter.getmDatas()){
                        boolean needAddBuild = false;
                        if (null != buildModel.getChildren() && buildModel.getChildren().size() > 0) {
                            for (XunChaFloorModel xunChaFloorModel : buildModel.getChildren()) {
                                // 不是全选按钮 当前为选中 未完成状态
                               if ("1".equals(xunChaFloorModel.getIsAllSelect())
                                       && "1".equals(xunChaFloorModel.getCurrentSelectStatus())
                                       && !"2".equals(xunChaFloorModel.getStatus())){
                                   floorIdList.add(xunChaFloorModel.getId());
                                   quesFloorIds.add(xunChaFloorModel.getFloorId());
                                   needAddBuild = true;
                               }
                            }
                        }
                        if (needAddBuild){
                            buildModel.setId(buildModel.getId());
                            xunChaBuildingModels.add(buildModel);
                        }
                    }
                }
                if (floorIdList.size() > 0){
                    if ("3".equals(xunChaPlanModel.getStatus())){
                        skipToXunChaItemPage();
                    }else {
                        initStartXunChaHttpHelper();
                    }
                }else {
                    ToastUtils.showToast(activity, "未选中楼层");
                }
            }
        });
    }

    private void setListData(List<XunChaBuildingModel> list) {
        baseRecyclerAdapter.clear();
        if (null == list || list.size() == 0){
            baseRecyclerAdapter.clear();
            include_no_data.setVisibility(View.VISIBLE);
            return;
        }
        include_no_data.setVisibility(View.GONE);

        for (XunChaBuildingModel xunChaBuildingModel:list){
            if (null != xunChaBuildingModel && xunChaBuildingModel.getChildren().size() > 1) {
                int size = 0;
                for (XunChaFloorModel xunChaFloorModel:xunChaBuildingModel.getChildren()){
                    // 楼层状态已完成
                    if ("2".equals(xunChaFloorModel.getStatus())){
                        size++;
                    }
                }
                // 多余一项未完成时显示全选
                if (!(size == xunChaBuildingModel.getChildren().size()) && !(size + 1 == xunChaBuildingModel.getChildren().size())){
                    XunChaFloorModel xunChaFloorModel = new XunChaFloorModel();
                    xunChaFloorModel.setFloorName("全选");
                    xunChaFloorModel.setIsAllSelect("0");
                    xunChaBuildingModel.getChildren().add(0, xunChaFloorModel);
                }
            }
        }
        baseRecyclerAdapter.addDatas(list);

        isAllChoose = false;
        iv_all_choose.setImageResource(R.mipmap.icon_all_choose);
    }

    /**
     * 获取列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", xunChaPlanModel.getId());
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XUNCHA_PLAN_STATUS_URL, CHECK_PLAN_STATUS_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 获取列表
     */
    private void initStartXunChaHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < floorIdList.size(); i++){
            if (i == 0){
                stringBuilder.append(floorIdList.get(i));
            }else {
                stringBuilder.append(","+floorIdList.get(i));
            }
        }
        hashMap.put("id", stringBuilder.toString());
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XUNCHA_START_URL, START_XUNCHA_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }


    private class InfoListListHttpHelper extends HttpHelper{

        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case CHECK_PLAN_STATUS_WHAT:
                    try {
                        LinkedList<XunChaBuildingModel> xunChaListModels = (LinkedList<XunChaBuildingModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(dataStr), XunChaBuildingModel.class);
                        bundle.putSerializable("list", xunChaListModels);
                        bundle.putBoolean(REQUEST_OK, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            if (msg.what == CHECK_PLAN_STATUS_WHAT) {
                include_progress_bar.setVisibility(View.GONE);
            }
            if (msg.what == START_XUNCHA_WHAT && ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                skipToXunChaItemPage();
                return;
            }
            return;
        }
        switch (msg.what){
            case CHECK_PLAN_STATUS_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                LinkedList<XunChaBuildingModel> list = (LinkedList<XunChaBuildingModel>) bundle.getSerializable("list");
                setListData(list);
                break;
        }
    }

    private void skipToXunChaItemPage() {
        BannerModel bannerModel = new BannerModel();
        bannerModel.setActionTitle(((ShowFragActivity)activity).tv_title.getText().toString());
        bannerModel.setActionType(ConstData.SHOWFRAG);
        bannerModel.setActionValue(ConstData.BARFLOOR);
        Bundle bundle = new Bundle();
        bundle.putSerializable("buildModelList", xunChaBuildingModels);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < floorIdList.size(); i++){
            if (i == 0){
                stringBuilder.append(floorIdList.get(i));
            }else {
                stringBuilder.append(","+floorIdList.get(i));
            }
        }
        bundle.putString("ids", stringBuilder.toString());
        StringBuilder floorIds = new StringBuilder();
        for (int i = 0; i < quesFloorIds.size(); i++){
            if (i == 0){
                floorIds.append(quesFloorIds.get(i));
            }else {
                floorIds.append(","+quesFloorIds.get(i));
            }
        }
        bundle.putString("floorIds", floorIds.toString());
        bundle.putSerializable("xunChaPlanModel", xunChaPlanModel);
        bundle.putString(ConstData.BARTYPE, "7");
        activity.setClickAction(bannerModel, bundle);
    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateData();
    }
}
